/*******************************************************************************
 *            SHOPPING CART COLLECTIONS CLASS EXTENDS COLLECTION CLASS
 ******************************************************************************/
function CartCollection() {
};
//inherit from Collection class
CartCollection.prototype = new Collection();
//reset the contructor after inheritance
CartCollection.prototype.constructor = CartCollection;

//augmenting the prototype

//overwriting the inherited add function
CartCollection.prototype.add = function (key, value) {
    var self = this;
    self.list[key] = {data: value};
    self.size++;
    self.fireCallbacks('add', key, value);
}

//overwriting the inherited remove function
CartCollection.prototype.remove = function (key) {
    var self = this;
    if (typeof self.list[key] != 'undefined') {
        delete self.list[key];
        self.size--;
        self.fireCallbacks('remove', key);
    }
}

//Create Data for Model
CartCollection.prototype.createModelData = function () {
    var self = this;
    var data = [];
    self.iterate(function (key, obj) {
        var id = key;

        data.push({
            contact_group_id: id
        });
    });

    return data;
}


CartCollection.prototype.getTotalContacts = function () {
    var self = this;
    var grand_total = 0
    self.iterate(function (key, obj) {
        var quantity = parseInt(obj.data.group_count);
        grand_total = grand_total + quantity;
    });
    return grand_total;
}


/*******************************************************************************
 *            END OF SHOPPING CART COLLECTIONS CLASS
 ******************************************************************************/

var SMS = {

    _cart: new CartCollection(),
    bulk_sender_id:'',

    init: function () {
        var self = this;

        self._cart.registerCallback('add', function (key, obj) {
            self.refreshCartUI();
        });

        self._cart.registerCallback('remove', function (key) {
            self.refreshCartUI();
        });

        self.configContactList();
        self.configSendSMS();

        // Character Counter
        jQuery("#sms_txt").charCount({
            count_type: 'up',
            counterText: 'Total Character: '
        });
       /* jQuery("#schedule_date").datepicker({
            inline: true,
            changeMonth: true,
            changeYear: true,
            showOn: "button",
            constrainInput: true,
            buttonText: "Click Here For Date"
        });*/
        //$("#schedule_date").datepicker( "option", "dateFormat", 'yy-mm-dd' );
        /*
        jQuery('#schedule_time').timepicker({
            minuteStep: 1,
            showMeridian:false
        });*/

        /*$('a[data-toggle="tab"]').on('shown', function (e) {
            var current_tab = $(e.target);// activated tab
            console.log(e.target);
           console.log(current_tab);
           // console.log(e.relatedTarget) // previous tab
        })*/

        $('a[data-toggle=tab]').click(function(){
            var current_tab = $(this).attr("href");
            if(current_tab == "#sms_import_tab"){
                $("#widget_contact_collection").hide();
                $("#widget_sms").hide();
                $("#stdformbutton").hide();
            }
            else{
                $("#widget_contact_collection").show();
                $("#widget_sms").show();
                $("#stdformbutton").show();
            }
        });
    },

    configContactList: function () {
        var self = this;

        //make the contact list selectable and the group as well
        $("#group_list_tab ul li,#cart_collection ul li").live('click', function (e) {
            var me = $(this);
            var span = me.find('span');
            if (me.hasClass('restrict')) {

            }
            else {
                if (me.hasClass('selected')) {
                    me.removeClass('selected');
                    span.removeClass('iconfa-check').addClass('iconfa-check-empty');
                }
                else {
                    me.addClass('selected');
                    span.removeClass('iconfa-check-empty').addClass('iconfa-check');
                }
            }

        });

        $("#select_all_btn").click(function (e) {
            var id = self.get_active_tab_id();
            $("#" + id + " ul li").each(function () {
                var me = $(this);
                var span = me.find('span');
                if (me.hasClass('restrict')) {

                }
                else {
                    me.addClass('selected');
                    span.removeClass('iconfa-check-empty').addClass('iconfa-check');
                }
            });
        });

        $("#unselect_all_btn").click(function (e) {
            var id = self.get_active_tab_id();
            $("#" + id + " ul li").each(function () {
                var me = $(this);
                var span = me.find('span');
                if (me.hasClass('restrict')) {

                }
                else {
                    me.removeClass('selected');
                    span.removeClass('iconfa-check').addClass('iconfa-check-empty');
                }

            });
        });

        $("#add_to_collection_btn").click(function (e) {
            $("#group_list_tab ul li.selected").each(function () {
                var me = $(this);
                var id = me.attr('data-id');
                var name = contacts_in_group[id]['name'];
                var g_count = contacts_in_group[id]['count'];
                //Add to collection
                self.updateCart('add', id, name, g_count);
            });
        });


        $("#remove_from_collection_btn").click(function (e) {
            $("#cart_collection ul li.selected").each(function () {
                var me = $(this);
                var id = me.attr('data-id');
                //Add to collection
                self.updateCart('remove', id);
            });
        });

        $("#remove_all_btn").click(function (e) {
            self.updateCart('clear');
        });
    },

    configSendSMS: function () {
        var self = this;

        $("#send_sms_btn").click(function () {
            if (self.validateSMS()) {
                self.send_SMS('Now');
            }
        });

        $("#send_sms_later_btn").click(function () {
            if (self.validateSMS()) {
                self.send_SMS('Later');
            }
        });

        $("#sms_schedule_modal_btn").click(function () {
            var credit_bal = parseFloat(credit_balance);
            var total_contacts = self._cart.getTotalContacts();
            var schedule_date = $('#schedule_year').val()+'-'+$('#schedule_month').val()+'-'+$('#schedule_day').val();
            var schedule_time = $('#schedule_time').val();
            schedule_date = schedule_date.trim();
            schedule_time = schedule_time.trim();
            if(schedule_date.length == 0 || schedule_time.length == 0 ){
                jLib.serverError("Schedule Date and Schedule Time are required!",false);
            }
            else{
                var schedule_date_time = schedule_date+' '+schedule_time;
                self.do_send_SMS('Later',credit_bal,total_contacts,schedule_date_time);
            }
        });

        $("#send_sms_import_btn").click(function () {
            jPrompt('Enter Sender ID (Up To 11 Alphanumeric Characters):', '', 'Sender ID', function(r) {
                r = r.trim();
                if( r ){
                    var len = r.length;
                    if(len > 11){
                        jLib.serverError("Sender ID must be Up To 11 Alphanumeric Characters !",false);
                    }
                    else{
                        self.bulk_sender_id = r;
                        $("#import_contact_group_btn").click();
                    }
                }
            });
        });
    },


    get_active_tab_id: function () {
        return $("div.tab-content div.active").attr('id');
    },


    updateCart: function (action, id, name, group_count) {
        var self = this;

        if (action == 'add') {
            self._cart.add(id, {
                id: id,
                name: name,
                group_count: group_count
            });
        }
        else if (action == 'remove') {
            self._cart.remove(id);
        }
        else {//Clear all
            self._cart.clear();
            self.refreshCartUI();
        }
    },


    refreshCartUI: function () {
        var self = this;

        $("#cart_collection ul").html('');
        self._cart.iterate(function (key, obj) {
            var id = key;
            var group_count = obj.data.group_count;
            var name = obj.data.name + ' (' + group_count + ' Contacts)';
            var li = $("<li />").attr('data-id', key);
            li.append($("<span />").attr('class', 'iconfa-envelope-alt'))
                .append('&nbsp;')
                .append(name)
            $("#cart_collection ul").append(li);
        });

        //show or hide buttons
        var size = self._cart.getSize();
        if (size <= 0) {
            $("#cart_collection_btns").hide();
        }
        else {
            $("#cart_collection_btns").show();
        }
    },


   /* getSMSCost: function () {
        var self = this;
        var unit_cost = parseFloat(sms_per_unit_cost);
        var per_count = parseInt(sms_per_unit_count);
        var total_contacts = self._cart.getTotalContacts();

        var sms_txt = $("#sms_txt").val();
        var txt_count = sms_txt.length;

        var messages_count = 0;
        var calc = true;
        while (calc) {
            if (txt_count > per_count) {
                txt_count = txt_count - per_count;
                messages_count++;
                calc = true;
            }
            else {
                txt_count = txt_count - per_count;
                messages_count++;
                calc = false;
            }
        }

        var total_cost_sms = (unit_cost * messages_count) * total_contacts;

        return total_cost_sms.toFixed(2);
    },*/


    validateSMS: function () {
        var self = this;
        var pass = true;

        var total_contacts = self._cart.getTotalContacts();
        var sms_txt = $("#sms_txt").val();
        var sender_id = $("#sender_id").val();

        var txt_count = sms_txt.length;
        var sender_txt_count = sender_id.length;
        if (txt_count == 0 || sender_txt_count == 0) {
            pass = false;
            var txt = "Text Message and Sender ID are required!"
            //Animate sms box
            $("#widget_sms .widgetcontent p.error").html(txt).show();
            $("#widget_sms").addClass('box-danger').addClass('animate0').addClass('bounceIn');
            setTimeout(function () {
                $("#widget_sms").removeClass('box-danger').removeClass('animate0').removeClass('bounceIn');
            }, 1000);
        }
        else {
            $("#widget_sms .widgetcontent p.error").html('').hide();
            $("#widget_sms").removeClass('box-danger').removeClass('animate0').removeClass('bounceIn');
        }

        if (total_contacts == 0) {
            pass = false;
            var txt = "Please select contacts from contact options!"
            //Animate sms box
            $("#widget_contact_collection .widgetcontent p.error").html(txt).show();
            $("#widget_contact_collection").addClass('box-danger').addClass('animate1').addClass('bounceIn');
            setTimeout(function () {
                $("#widget_contact_collection").removeClass('box-danger').removeClass('animate1').removeClass('bounceIn');
            }, 1000);
        }
        else {
            $("#widget_contact_collection .widgetcontent p.error").html('').hide();
            $("#widget_contact_collection").removeClass('box-danger').removeClass('animate1').removeClass('bounceIn');
        }

        return pass
    },


    send_SMS: function (schedule) {
        var self = this;

        var credit_bal = parseFloat(credit_balance);
        var total_contacts = self._cart.getTotalContacts();

        if(schedule == 'Later'){
            var current_date = new Date();
            var year = current_date.getFullYear();
            var month = current_date.getMonth();
            var day  = current_date.getDate();
            var hour = current_date.getHours();
            var min = current_date.getMinutes();
            $("#sms_schedule_modal form")[0].reset();

            $("#sms_schedule_modal #schedule_date").val(year+'-'+month+'-'+day);
            $("#sms_schedule_modal #schedule_time").val(hour+':'+min);

            $('#sms_schedule_modal').modal({
                backdrop: 'static',
                show: true,
                keyboard: true
            });
            var d = new Date();
            d.setMinutes(d.getMinutes() + 10);
            var time_10_min = d.getHours()+":"+ d.getMinutes();
            $("#schedule_time").val(time_10_min);
        }
        else{
            self.do_send_SMS(schedule,credit_bal,total_contacts);
        }
    },


    do_send_SMS: function (schedule,credit_bal,total_contacts,schedule_date) {
        var self = this;

        var ms = "You are about to send SMS to "+total_contacts+" contacts. Click OK if you want to proceed or Cancel if you want to quit.";

        jConfirm(ms, 'Confirm', function(confirmation) {
            if(confirmation){
                var save = {
                    sms: $("#sms_txt").val(),
                    sender_id:$("#sender_id").val(),
                    groups:self._cart.createModelData(),
                    total_contacts:total_contacts,
                    'schedule':schedule
                }
                var close_schedule = false;
                if(typeof schedule_date != "undefined" ){
                    save['schedule_date'] = schedule_date;
                    close_schedule = true;
                }

                var url = $('#do-sms-url').val();
                var query = 'data=' + encodeURIComponent(JSON.stringify(save));

                $.ajax({
                    url:url,
                    data:query,
                    dataType:'json',
                    type:'POST',
                    success:function (response) {
                        var txt = '';
                        if (typeof response.msg == 'object') {
                            for (megTxt in response.msg) {
                                txt += response.msg[megTxt] + '<br />';
                            }
                        }
                        else {
                            txt = response.msg
                        }
                        //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                        if (response.code === 0) {
                            jLib.serverSuccess(txt);
                            //Update Credit Balance
                            jLib.updateCreditBal(response.new_credit_bal);
                            self.clearSMSForm(close_schedule);
                        }
                        //* When there are Errors *//*
                        else if (response.code === 1) {
                            jLib.serverError(txt,false);
                        }
                    },
                    error:function (xhr) {
                        jLib.serverError();
                    }
                });
            }
        });
    },


    clearSMSForm:function(close_schedule){
        var self = this;

        $("#sms_txt").val('').keyup();
        $("#sender_id").val('');
        $("#unselect_all_btn").click();
        $("#remove_all_btn").click();
        if(close_schedule){
            $("#close-sms_schedule_modal").click();
        }
    },

    import_extra_param:function(p){
        var self = this;
        //You can even change the data to pass dynamically before this function get called by the file upload manager
        var params={
            sender_id:self.bulk_sender_id
        };
        return params;
    },

    import_callback:function(p){
        var self = this;
        var file = p.files[0];
        if(typeof file.error !="undefined"){ //Error
            jLib.serverError(file.error,false);
        }
        else{ //Success
            jLib.serverSuccess(file.success);
            //Update Credit Balance
            jLib.updateCreditBal(file.credit_bal);
        }
    }

};

/* when the page is loaded */
$(document).ready(function () {
    SMS.init();
});

function func_extra_param(){
    return SMS.import_extra_param();
}

function func_callback(p){
    return SMS.import_callback(p);
}
